package com.tzu.ft.transfer;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import com.tzu.ft.base.FTConfig;
import com.tzu.ft.transfer.server.FTSSLServer;
import com.tzu.ft.transfer.server.FTServer;
import com.tzu.ft.transfer.server.Server;
import com.tzu.ft.ui.FTUI;
import com.tzu.ssl.KeyInfo;

public class ServerTaskFactory {

    private static ThreadPoolExecutor threadPoolExecutor;

    private static Map<String, Socket> SERVER_TASK_MAP = new HashMap<>();

    private static KeyInfo keyInfo;

    private static Server server;

    public static FTUI uimain;

    public static void init(int port, boolean ssl, FTUI uimain) throws Exception {
        ServerTaskFactory.uimain = uimain;
        // 加密
        if (ssl) {
            server = new FTSSLServer();
            keyInfo = FTConfig.getKeyInfo();
            server.init(port, keyInfo);
        } else {
            server = new FTServer();
            server.init(port, null);
        }

        // 获取默认线程池配置
        int threads = FTConfig.getTaskThreadNum();
        threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(threads);

        // 启动服务
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    server.start();
                } catch (Exception e) {
                    String em = e.getMessage();
                    if (!em.contains("socket closed")) {
                        e.printStackTrace();
                    }
                }
            }
        };
        thread.start();
    }

    public static Server getServer() {
        return server;
    }

    public static void addTask(ServerTaskRunning running) throws Exception {
        Socket socket = running.getSocket();
        SERVER_TASK_MAP.put(socket.hashCode() + "", socket);

        //如果超过默认长度，则会排队
        threadPoolExecutor.execute(running);

//        int active = threadPoolExecutor.getActiveCount();
//        if (active < FTConfig.getMaxThreads()) {
//            threadPoolExecutor.execute(running);
//        } else {
//            throw new Exception("并行队列已经到达最大值，无法接收任务");
//        }
    }

    /**
     * 销毁
     *
     * @throws Exception
     */
    public static void destoryServer() {
        List<String> keylist = new ArrayList<String>(SERVER_TASK_MAP.keySet());
        for (String key : keylist) {
            try {
                Socket socket = SERVER_TASK_MAP.get(key);
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (null != server) {
            try {
                server.exit();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        SERVER_TASK_MAP.clear();
        if (null != threadPoolExecutor) {
            threadPoolExecutor.shutdown();
            threadPoolExecutor = null;
        }

    }

    /**
     * 销毁
     */
    public static void destory(ServerTaskRunning running) {
        try {
            if (null != running) {
                Socket socket = running.getSocket();
                if (null != socket) {
                    SERVER_TASK_MAP.remove(socket.hashCode() + "");
                    socket.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("当前任务数：" + getTaskCount());
    }


    public static long getTaskCount() {
        if (null != threadPoolExecutor) {
            return threadPoolExecutor.getActiveCount();
        }
        return 0;
    }

}
